﻿/// <reference path="C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\MicrosoftAjax.js" />
/// <reference path="C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\SP.Core.debug.js" />
/// <reference path="C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\SP.debug.js" />
/// <reference path="~/SiteAssets/AIR/js/air.js" />

/**	
	Credits:
		JSON Prettification: WarFares https://github.com/warfares/pretty-json
		Tag Cloud: Adam Groves https://github.com/addywaddy/jquery.tagcloud.js
		jsRender: Borris Moore http://github.com/BorisMoore/jsrender
		Underscore: Jeremy Ashkenas http://underscorejs.org/
**/

Type.registerNamespace("Pdogs.Air");

Pdogs.Air.QueryOpts = function (querytext) {
	var qtext = querytext;

	return {
	};
};

Pdogs.Air.App = function () {
	var baseUrl = _spPageContextInfo.webServerRelativeUrl.trimEnding('/') + '/_vti_bin/listdata.svc/',
		currentList = '',
		ctx = null,
		lists = [],
		columns = [],

		initApp = function () {
			columns = [];
			lists = [];
			ctx = SP.ClientContext.get_current();
			var listCol = ctx.get_web()
								.get_lists();
			ctx.load(listCol);
			ctx.executeQueryAsync(function () {
				var en = listCol.getEnumerator();
				while (en.moveNext()) {
					var l = en.get_current();
					var t = l.get_baseType();
					if (l.get_hidden() == true || (t != 0 && t != 1)) continue;
					lists.push({
						Title: l.get_title(),
						ID: l.get_id()
					});
				}
				setupUI();
			}, Pdogs.Air.Utils.onJsomError);
		},
		setupUI = function () {
			$("#query")
				.blur(refreshDisplayUrl);
			$('#air-leftinner a')
				.tagcloud();
			$('A.resttag')
				.click(onClickRestTag)
				.tooltip();
			$('#run')
				.button({ icons: { primary: "ui-icon-power" }, text: true })
				.click(onClickRunQuery);
			$("#query").on("keypress", function (e) {
				if (e.which == 13) {
					e.preventDefault();
					return onClickRunQuery(e);
				}
			});
			$('#resturlcopy')
				.button({ icons: { primary: "ui-icon-copy" }, text: false })
				.click(onClickResturlCopy)
				.next('div').html(getBaseUrl());
			$("#listtitle")
				.blur(onManualEnterListTitle)
				.tooltip();
			buildListsUI();

			$("#col-dialog").dialog({
				autoOpen: false,
				height: 140,
				width: 350,
				modal: true,
				buttons: {
					"$select ": function () {
						addColumnToRest($("#col-dialog-name").html(), '$select');
						$(this).dialog("close");
					},
					"$orderby": function () {
						addColumnToRest($("#col-dialog-name").html(), '$orderby');
						$(this).dialog("close");
					},
					"$filter ": function () {
						addColumnToRest($("#col-dialog-name").html(), '$filter');
						$(this).dialog("close");
					},
					Cancel: function () {
						$(this).dialog("close");
					}
				}
			});
		},
		buildListsUI = function () {
			$("#lists").empty();
			if (lists.length < 1) return;

			var renderingTemplate = "<li><a listid='{{>ID}}'>{{>Title}}</a></li>";
			$.templates({ "listtmpl": renderingTemplate });
			$("#lists")
				.append("<li><a listid='' style='font-style:italic;'>-- Clear List Selection --</a></li>")
				.append($.render.listtmpl(lists));
			$("#listsmenu")
				.menu({
					select: onSelectList
				});
		},
		onSelectList = function (event, ui) {
			if (ui.item.find("a").attr('id') === 'choose') return false;
			if (ui.item.find("a").attr('listid') === '') {
				$("#listtitle").val('');
				setCurrentList('');
				return false;
			}

			$("#listtitle").val(ui.item.text());
			setCurrentList(ui.item.text());
		},
		onManualEnterListTitle = function () {
			setCurrentList($("#listtitle").val());
		},
		setCurrentList = function (listname) {
			columns = [];
			Pdogs.Air.Utils.clearError();

			currentList = listname;
			refreshDisplayUrl();

			if (typeof (listname) === 'undefined' || listname == null || listname === '') {
				buildListColumnsUI();
				return false;
			}

			/* get columns for list */
			var fieldCol = ctx.get_web()
								.get_lists()
								.getByTitle(currentList)
								.get_fields();
			ctx.load(fieldCol);
			ctx.executeQueryAsync(function () {
				var en = fieldCol.getEnumerator();
				while (en.moveNext()) {
					var f = en.get_current();
					if (f.get_hidden() == true) continue;
					var ft = f.get_typeAsString();
					columns.push({
						Title: f.get_title(),
						ID: f.get_id(),
						Description: f.get_description(),
						Type: f.get_typeAsString(),
						RequireExpand: (ft === 'Choice'
										|| ft === 'User'
										|| ft === 'UserMulti'
										|| ft === 'Lookup'
										|| ft === 'LookupMulti')
					});
				}
				buildListColumnsUI();
			}, Pdogs.Air.Utils.onJsomError);
			return false;
		},
		buildListColumnsUI = function () {
			$("#columns").empty();
			if (columns.length < 1) return;

			var renderingTemplate = "<a href='#' rel='2' class='resttag' fid='{{>ID}}'>{{>Title}}</a>";
			$.templates({ "columntmpl": renderingTemplate });
			$("#columns")
				.append($.render.columntmpl(columns));
			$('#columns a')
				.tagcloud();
			$('#columns a.resttag')
				.click(onClickColumnTag);
		},
		getBaseUrl = function () {
			var u = baseUrl;
			if (currentList != '') u = u + currentList.replace(/ /g, '');
			return u;
		},
		getRestUrl = function () {
			var u = getBaseUrl();
			var q = $("#query").val();
			if (q != null && q.length > 0) {
				q = q.replace(/\r\n/g, '');
				if (q === '$metadata' || q === '$count') {
					u = u.trimEnding('/') + '/' + q;
				} else if (q[0] != '(' && q != '/$count')
					u = u + '?' + q;
				else {
					if (q.indexOf('/$value') > -1)
						u = u + q;
					else {
						u = u + q;
					}
				}
			}
			return u;
		},
		refreshDisplayUrl = function () {
			var u = getRestUrl();
			$('#resturlcopy')
				.next('div').html(u);
		},
		onClickRestTag = function (e) {
			e.preventDefault();
			var tag = $(this).html();
			var itag = $(this).attr('itag') || tag;

			var q = $("#query");
			var qtxt = q.val().trimStarting(' ').trimEnding(' ');
			if (tag[0] == '$') {
				if (qtxt.indexOf(tag) > -1) return false;
				if (tag === '$metadata') {
					q.val(itag);
					return false;
				}

				if (tag != '$value' && qtxt.length > 0)
					itag = '&' + itag;
			} else if (tag === 'datetime') {
				var d = new Date();
				itag = "datetime'" + d.format('yyyy-MM-ddThh:mm:ssZ') + "'";
			} else if (tag === 'time') {
				var d = new Date();
				itag = "time'" + d.format('hh:mm:ss') + "'";
			} else if (tag === 'guid') {
				itag = "guid'1225c695-cfb8-4ebb-aaaa-80da344efa6a'";
			}

			if (qtxt.length < 1) itag = itag.trimStarting(' ');
			q.val(qtxt + itag);
			return false;
		},
		onClickColumnTag = function (e) {
			e.preventDefault();
			$("#col-dialog-name").html($(this).html());
			$("#col-dialog").dialog("open");
			return false;
		},
		addColumnToRest = function (column, toparameter) {
			var q = $("#query");
			var qt = q.val() || '';

			var col = column.replace(/ /g, '');
			if (col === 'ID')
				col = 'Id'; // weird that SP Rest doesn't recognise the ID column!!

			var sep = ',';
			if (toparameter === '$filter')
				sep = ' and ';
			else if (toparameter === '$orderby') {
				col += ' asc';
			}

			var p = toparameter + '=';
			var i = qt.indexOf(p);
			if (i > -1) {
				qt = qt.substring(0, i + p.length) + col + sep + qt.substring(i + p.length);
			} else {
				if (qt.length > 0)
					qt = qt + '&' + p + col;
				else
					qt = p + col;
			}
			q.val(qt);
			if (toparameter === '$select') {
				var colObj = $.grep(columns, function (item, i) {
					return item.Title === column;
				});
				if ((colObj.length > 0) && (colObj[0].RequireExpand)
										) {
					addColumnToRest(column, '$expand');
				}
			}
		},
		onClickResturlCopy = function (e) {
			try {
				window.clipboardData.setData('Text', $('#resturl > div').html());
			}
			catch (e) {
				alert("Sorry, looks like you're (sensibly) not using IE.\n\nDoing it the old way, select the text right click and copy.");
			}
		},
		onClickRunQuery = function (e) {
			e.preventDefault();
			var requestUri = getRestUrl();
			refreshDisplayUrl();

			$("#results")
				.html("<img src='/_layouts/images/loadingcirclests16.gif' style='vertical-align: top;' /> Query Inprogress...");
			Pdogs.Air.Utils.clearError();

			$.getJSON(requestUri)
				.done(onRestDataReturned)
				.fail(function (error) {
					if (error.status === 200)
						onRestDataReturned(error.responseText);
					else {
						$("#results").empty();
						Pdogs.Air.Utils.onAjaxError(error, requestUri);
					}
				});

			return false;
		},
		onRestDataReturned = function (data) {
			try {
				var jsonResults = typeof (data) === 'object'
									? data
									: data.startsWith('<?xml ')
										? Pdogs.Air.Utils.xmlToJson(Pdogs.Air.Utils.parseXml(data))
										: { "$value": data };
				var node = new PrettyJSON.view.Node({
					el: $("#results"),
					data: jsonResults
				});
			}
			catch (e) {
				Pdogs.Air.Utils.userException(null, e, 'Exception prettifying JSON results!');
			}
		};

	return {
		initApp: initApp
	};
}();

$.fn.tagcloud.defaults = {
	size: { start: 9, end: 12, unit: 'pt' },
	color: { start: '#0072C6', end: '#C65300' }
};

Pdogs.Air.Utils.set_errorSelector('#error');
SP.SOD.executeOrDelayUntilScriptLoaded(Pdogs.Air.App.initApp, "SP.js");
